package cn.xval.ft.core.marketdata.manage.method;

import cn.xval.ft.core.ctp.CThostFtdcDepthMarketDataField;
import cn.xval.ft.core.ctp.CThostFtdcRspInfoField;
import cn.xval.ft.core.ctp.CThostFtdcSpecificInstrumentField;
import cn.xval.ft.core.marketdata.manage.MarketDataSpi;
import cn.xval.ft.core.marketdata.manage.SpiManager;
import cn.xval.ft.core.marketdata.manage.SpiStatus;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class Subscriber {
    private MarketDataSpi spi;

    public Subscriber(MarketDataSpi spi) {
        this.spi = spi;
    }

    public void doSubscribe(List<String> instruments) {
        spi.getConnect().SubscribeMarketData(instruments.toArray(new String[0]), instruments.size());
    }

    public void onRspSubMarketData(CThostFtdcSpecificInstrumentField pSpecificInstrument, CThostFtdcRspInfoField pRspInfo, int nRequestID, boolean bIsLast) {
        var bSuccess = pRspInfo != null && pRspInfo.getErrorID() == 0;
        if (bSuccess) {
            spi.setCurrentStatus(SpiStatus.subscribeOk)
                    .setExtra(pSpecificInstrument.getInstrumentID());
            log.info("行情订阅成功,合约代码: {}", pSpecificInstrument.getInstrumentID());
            SpiManager.updateWatchingState(pSpecificInstrument.getInstrumentID(), true);
            return;
        }

        if (pRspInfo != null) {
            spi.setCurrentStatus(SpiStatus.subscribeFailedByLogic).setExtra("%d: %s".formatted(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()));
            log.error("行情订阅失败 -> id: {}, message: {}", pRspInfo.getErrorID(), pRspInfo.getErrorMsg());
        }
        else {
            spi.setCurrentStatus(SpiStatus.subscribeFailedByNet);
            log.error("行情订阅失败 -> 未知错误");
        }
        if (pSpecificInstrument != null) {
            SpiManager.updateWatchingState(pSpecificInstrument.getInstrumentID(), false);
        }
    }

    /// 派发数据
    public void onRtnDepthMarketData(CThostFtdcDepthMarketDataField pDepthMarketData) {
        SpiManager.dispatchMarketData(pDepthMarketData);
    }
}
